package com.simple_frame.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;

/**
 * @author zhanghaifeng
 */
@Component
@Slf4j
public class MailUtil {

    @Value("${spring.mail.username}")
    private String sender; // 邮件发送者

    @Resource
    private JavaMailSender javaMailSender;


    /**
     * 发送文本邮件
     *
     * @param address 接收地址
     * @param title   主题
     * @param message 具体内容
     */
    public void send(String address, String title, String message) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(sender); // 邮件发送者
            mailMessage.setTo(address); // 邮件发给的人
            mailMessage.setSubject(title);  // 邮件主题
            mailMessage.setText(message);  // 邮件内容
            javaMailSender.send(mailMessage);
        } catch (Exception e) {
            log.error("邮件发送失败 {}", e.getMessage());
            throw new RuntimeException("发送失败");
        }
    }

}
